import pygame
from typing import List, Tuple, Callable
from ..theme import Theme
from ..word_bank import WordBank
from ..user_profile import UserProfile
import time

class MenuView:
    def __init__(self, screen: pygame.Surface, theme: Theme, word_bank: WordBank, user_profile: UserProfile):
        self.screen = screen
        self.theme = theme
        self.word_bank = word_bank
        self.user_profile = user_profile
        
        # 如果没有当前用户，显示用户选择/创建界面
        self.show_user_selection = not user_profile.current_user
        
        # 菜单选项
        self.menu_items = [
            ("练习模式", "practice"),
            ("学习模式", "study"),
            ("统计信息", "stats"),
            ("词库管理", "wordbank"),
            ("退出", "quit")
        ]
        
        # 用户选择界面的按钮
        self.user_buttons = []
        self.new_user_button = None
        
        # 界面尺寸
        self.width = screen.get_width()
        self.height = screen.get_height()
        
        # 菜单选项和说明
        self.options: List[Tuple[str, Callable, str]] = [
            ("练习模式", lambda: "practice", "随机抽取单词进行打字练习，提高输入速度"),
            ("学习模式", lambda: "study", "按艾宾浩斯遗忘曲线复习单词，提高记忆效果"),
            ("选择词库", lambda: "wordbank", "选择不同难度和类型的词库进行学习"),
            ("统计信息", lambda: "stats", "查看学习进度和练习成绩"),
            ("退出", lambda: "quit", "退出程序")
        ]
        
        self.selected = 0
        
        # 将按钮存储改为字典，并添加一个方法来清理临时按钮
        self.buttons = {}
        self.temp_buttons = {}  # 用于存储临时按钮（如对话框按钮）
        
        # 菜单按钮的位置
        start_y = 250
        button_width = 200  # 增加按钮宽度
        button_height = 50  # 增加按钮高度，更易点击
        button_x = self.width/2 - 250  # 左移按钮位置，留出更多空间给描述
        for i in range(len(self.options)):
            self.buttons[f"menu_{i}"] = pygame.Rect(
                button_x, 
                start_y + i*(button_height + 15), 
                button_width, 
                button_height
            )
            
        # 如果需要显示用户选择界面，加载用户列表
        if self.show_user_selection:
            self.refresh_user_list()
        
        # 添加用户创建对话框状态
        self.show_create_user_dialog = False
        self.new_username_input = ""
        self.input_active = False
        
    def refresh_user_list(self) -> None:
        """刷新用户列表"""
        # 清理临时按钮
        self._clear_temp_buttons()
        
        # 获取所有用户
        users = self.user_profile.list_users()
        
        # 创建用户按钮
        self.user_buttons = []
        start_y = 150
        button_width = 250
        button_height = 60
        button_gap = 20
        
        for i, user in enumerate(users):
            button = pygame.Rect(
                self.width/2 - button_width/2,
                start_y + i*(button_height + button_gap),
                button_width, button_height
            )
            self.user_buttons.append((button, user))
        
        # 创建"新建用户"按钮
        self.new_user_button = pygame.Rect(
            self.width/2 - button_width/2,
            start_y + len(users)*(button_height + button_gap) + button_gap,
            button_width, button_height
        )
        
    def handle_event(self, event: pygame.event.Event) -> str:
        """处理事件"""
        # 首先处理创建用户对话框的事件
        if self.show_create_user_dialog:
            if event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                
                # 计算对话框位置
                dialog_width = 400
                dialog_height = 250  # 增加高度，使布局更加宽松
                dialog_x = self.width/2 - dialog_width/2
                dialog_y = self.height/2 - dialog_height/2
                dialog_rect = pygame.Rect(dialog_x, dialog_y, dialog_width, dialog_height)
                
                # 如果点击对话框外部，关闭对话框
                if not dialog_rect.collidepoint(mouse_pos):
                    self.show_create_user_dialog = False
                    self.new_username_input = ""
                    self.input_active = False
                    return None
                
                # 检查输入框点击
                input_rect = pygame.Rect(dialog_x + 50, dialog_y + 80, 300, 45)
                if input_rect.collidepoint(mouse_pos):
                    self.input_active = True
                    return None
                else:
                    self.input_active = False
                
                # 检查确认按钮
                if self.temp_buttons.get("create_confirm") and \
                   self.temp_buttons["create_confirm"].collidepoint(mouse_pos):
                    if self.new_username_input.strip():
                        if self.user_profile.load_profile(self.new_username_input):
                            self.show_user_selection = False
                            self.show_create_user_dialog = False
                            self.new_username_input = ""
                            self.input_active = False
                            self.refresh_user_list()
                    return None
                
                # 检查取消按钮
                if self.temp_buttons.get("create_cancel") and \
                   self.temp_buttons["create_cancel"].collidepoint(mouse_pos):
                    self.show_create_user_dialog = False
                    self.new_username_input = ""
                    self.input_active = False
                    return None
            
            elif event.type == pygame.KEYDOWN and self.input_active:
                if event.key == pygame.K_RETURN:
                    if self.new_username_input.strip():
                        if self.user_profile.load_profile(self.new_username_input):
                            self.show_user_selection = False
                            self.show_create_user_dialog = False
                            self.new_username_input = ""
                            self.input_active = False
                            self.refresh_user_list()
                elif event.key == pygame.K_BACKSPACE:
                    self.new_username_input = self.new_username_input[:-1]
                elif event.key == pygame.K_ESCAPE:
                    self.show_create_user_dialog = False
                    self.new_username_input = ""
                    self.input_active = False
                else:
                    # 只接受合法的用户名字符
                    if event.unicode.isalnum() or event.unicode in ['_', '-']:
                        self.new_username_input += event.unicode
            return None
        
        # 然后处理用户选择界面的事件
        if self.show_user_selection:
            if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                mouse_pos = pygame.mouse.get_pos()
                
                # 检查用户按钮
                for button, username in self.user_buttons:
                    if button.collidepoint(mouse_pos):
                        if self.user_profile.load_profile(username):
                            self.show_user_selection = False
                        return None
                
                # 检查新建用户按钮
                if self.new_user_button and self.new_user_button.collidepoint(mouse_pos):
                    self.show_create_user_dialog = True
                    self.input_active = True  # 自动激活输入框
                    return None
            return None
        
        # 最后处理主菜单的事件
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                self.selected = (self.selected - 1) % len(self.options)
            elif event.key == pygame.K_DOWN:
                self.selected = (self.selected + 1) % len(self.options)
            elif event.key == pygame.K_RETURN:
                action = self.options[self.selected][1]()
                # 检查是否需要用户登录
                if action == "study" and not self.user_profile.current_user:
                    self.show_user_selection = True
                    return None
                return action
                
        elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            mouse_pos = pygame.mouse.get_pos()
            for i in range(len(self.options)):
                if self.buttons[f"menu_{i}"].collidepoint(mouse_pos):
                    self.selected = i
                    action = self.options[i][1]()
                    # 检查是否需要用户登录
                    if action == "study" and not self.user_profile.current_user:
                        self.show_user_selection = True
                        return None
                    return action
        
        return None
        
    def draw(self):
        """绘制菜单"""
        # 清空屏幕
        self.screen.fill(self.theme.background_color)
        
        # 如果需要选择用户
        if self.show_user_selection:
            self._draw_user_selection()
            return
        
        # 绘制标题卡片
        title_card_rect = pygame.Rect(self.width/2 - 300, 50, 600, 100)
        self.theme.draw_card(self.screen, title_card_rect, with_shadow=True)
        
        # 绘制标题
        title = "打字背单词"
        self.theme.draw_text(
            self.screen, 
            title, 
            (self.width/2, 100), 
            center=True, 
            size=48, 
            color=self.theme.primary_color,
            shadow=True
        )
        
        # 绘制菜单背景卡片
        menu_card_rect = pygame.Rect(50, 180, self.width - 100, 400)
        self.theme.draw_card(self.screen, menu_card_rect, with_shadow=True)
        
        # 绘制菜单选项
        start_y = 250
        button_height = 50
        button_gap = 15
        desc_x = self.width/2 + 50
        
        for i, (text, _, description) in enumerate(self.options):
            button = self.buttons[f"menu_{i}"]
            
            # 确定按钮状态
            is_hover = i == self.selected
            
            # 使用新的按钮绘制方法
            self.theme.draw_button(
                self.screen, 
                button, 
                text, 
                is_hover=is_hover
            )
            
            # 绘制说明文字（右侧）
            self.theme.draw_text(
                self.screen, 
                description, 
                (desc_x, start_y + i*(button_height + button_gap) + button_height/2), 
                center=False, 
                color=self.theme.text_color, 
                size=16
            )
        
        # 绘制操作说明卡片
        help_card_rect = pygame.Rect(20, self.height - 120, 180, 100)
        self.theme.draw_rounded_rect(
            self.screen, 
            help_card_rect, 
            (*self.theme.card_bg_color[:3], 200),  # 半透明
            border=1
        )
        
        # 绘制操作说明
        instructions = [
            "↑↓: 选择",
            "Enter: 确认",
            "鼠标: 点击选择"
        ]
        for i, instruction in enumerate(instructions):
            self.theme.draw_text(
                self.screen, 
                instruction,
                (help_card_rect.left + 20, help_card_rect.top + 25 + i*25), 
                size=16,
                color=self.theme.text_color
            ) 

    def _draw_user_selection(self):
        """绘制用户选择界面"""
        # 绘制标题卡片
        title_card_rect = pygame.Rect(self.width/2 - 200, 30, 400, 80)
        self.theme.draw_card(self.screen, title_card_rect, with_shadow=True)
        
        # 绘制标题
        self.theme.draw_text(
            self.screen, 
            "选择用户", 
            (self.width/2, 70), 
            center=True, 
            size=36,
            color=self.theme.primary_color
        )
        
        # 绘制用户列表背景卡片
        if self.user_buttons or self.new_user_button:
            users_card_height = len(self.user_buttons) * 80 + 120  # 为新建按钮留出空间
            users_card_rect = pygame.Rect(
                self.width/2 - 200, 
                140, 
                400, 
                users_card_height
            )
            self.theme.draw_card(self.screen, users_card_rect, with_shadow=True)
        
        # 绘制用户列表
        if not self.user_buttons:
            self.theme.draw_text(
                self.screen, 
                "没有找到用户档案",
                (self.width/2, self.height/2 - 50),
                center=True, 
                size=24,
                color=self.theme.text_color
            )
        else:
            for i, (button, username) in enumerate(self.user_buttons):
                # 检测鼠标悬停
                mouse_pos = pygame.mouse.get_pos()
                is_hover = button.collidepoint(mouse_pos)
                
                # 绘制用户按钮
                self.theme.draw_button(
                    self.screen, 
                    button, 
                    username, 
                    is_hover=is_hover
                )
        
        # 绘制新建用户按钮
        if self.new_user_button:
            # 检测鼠标悬停
            mouse_pos = pygame.mouse.get_pos()
            is_hover = self.new_user_button.collidepoint(mouse_pos)
            
            # 使用强调色
            color = self.theme.accent_color if is_hover else self.theme.secondary_color
            
            # 绘制按钮
            self.theme.draw_rounded_rect(
                self.screen, 
                self.new_user_button, 
                color
            )
            
            self.theme.draw_text(
                self.screen, 
                "新建用户",
                (self.new_user_button.centerx, self.new_user_button.centery),
                center=True, 
                size=24,
                color=self.theme.button_text_color
            )
        
        # 如果显示创建用户对话框
        if self.show_create_user_dialog:
            self._draw_create_user_dialog()

    def _draw_create_user_dialog(self):
        """绘制创建用户对话框"""
        # 清理之前的临时按钮
        self._clear_temp_buttons()
        
        # 创建半透明遮罩
        overlay = pygame.Surface((self.width, self.height))
        overlay.fill((0, 0, 0))
        overlay.set_alpha(128)
        self.screen.blit(overlay, (0, 0))
        
        # 对话框尺寸和位置
        dialog_width = 400
        dialog_height = 250  # 增加高度，使布局更加宽松
        dialog_x = self.width/2 - dialog_width/2
        dialog_y = self.height/2 - dialog_height/2
        
        # 绘制对话框背景（使用卡片绘制）
        dialog_rect = pygame.Rect(dialog_x, dialog_y, dialog_width, dialog_height)
        self.theme.draw_card(self.screen, dialog_rect, with_shadow=True)
        
        # 绘制标题
        self.theme.draw_text(
            self.screen,
            "创建新用户",
            (self.width/2, dialog_y + 40),
            center=True,
            size=28,
            color=self.theme.primary_color
        )
        
        # 绘制输入框提示文本
        self.theme.draw_text(
            self.screen,
            "请输入用户名",
            (dialog_x + 50, dialog_y + 80),
            center=False,
            size=18,
            color=self.theme.text_color
        )
        
        # 绘制输入框
        input_rect = pygame.Rect(dialog_x + 50, dialog_y + 110, 300, 45)
        border_color = self.theme.primary_color if self.input_active else self.theme.border_color
        self.theme.draw_rounded_rect(
            self.screen, 
            input_rect, 
            self.theme.card_bg_color, 
            border=2, 
            border_color=border_color
        )
        
        # 计算文本位置
        text_y = input_rect.centery
        text_pos = (input_rect.left + 15, text_y)
        
        # 绘制输入的文本
        if self.new_username_input:
            self.theme.draw_text(
                self.screen,
                self.new_username_input,
                text_pos,
                center=False,
                size=20
            )
        elif not self.input_active:
            # 如果没有输入内容且输入框未激活，显示灰色提示
            self.theme.draw_text(
                self.screen,
                "点击此处输入",
                text_pos,
                center=False,
                size=20,
                color=(160, 160, 160)
            )
        
        # 如果输入框处于活动状态，绘制光标
        if self.input_active and time.time() % 1 > 0.5:
            cursor_x = text_pos[0]
            if self.new_username_input:
                cursor_x += self.theme.get_text_width(self.new_username_input, size=20)
            
            # 调整光标高度以匹配文本
            cursor_top = text_y - 12
            cursor_bottom = text_y + 12
            
            pygame.draw.line(
                self.screen,
                self.theme.primary_color,  # 使用主题色作为光标颜色
                (cursor_x, cursor_top),
                (cursor_x, cursor_bottom),
                2  # 增加线宽
            )
        
        # 绘制按钮
        button_y = dialog_y + dialog_height - 70
        button_width = 130
        button_height = 45
        
        # 确认按钮
        confirm_rect = pygame.Rect(dialog_x + 60, button_y, button_width, button_height)
        self.theme.draw_button(
            self.screen, 
            confirm_rect, 
            "确认", 
            is_active=True
        )
        self.temp_buttons["create_confirm"] = confirm_rect
        
        # 取消按钮
        cancel_rect = pygame.Rect(dialog_x + 210, button_y, button_width, button_height)
        
        # 使用带边框的样式
        self.theme.draw_rounded_rect(
            self.screen, 
            cancel_rect, 
            self.theme.card_bg_color,
            border=2,
            border_color=self.theme.border_color
        )
        
        self.theme.draw_text(
            self.screen,
            "取消",
            (cancel_rect.centerx, cancel_rect.centery),
            center=True,
            size=20,
            color=self.theme.text_color
        )
        self.temp_buttons["create_cancel"] = cancel_rect

    def _clear_temp_buttons(self):
        """清理临时按钮"""
        self.temp_buttons.clear() 